"""6.2.0 update progress_invoicing cascade

Revision ID: 82443e7fc843
Revises: 1ad5591c5c90
Create Date: 2021-06-21 17:54:56.647323

"""

# revision identifiers, used by Alembic.
revision = "82443e7fc843"
down_revision = "1ad5591c5c90"

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from caerp.alembic.utils import foreign_key_exists


def update_database_structure():
    if foreign_key_exists(
        "progress_invoicing_line", "fk_progress_invoicing_line_task_line_id"
    ):
        op.drop_constraint(
            op.f("fk_progress_invoicing_line_task_line_id"),
            "progress_invoicing_line",
            type_="foreignkey",
        )
    op.create_foreign_key(
        op.f("fk_progress_invoicing_line_task_line_id"),
        "progress_invoicing_line",
        "task_line",
        ["task_line_id"],
        ["id"],
        ondelete="CASCADE",
    )
    if foreign_key_exists(
        "progress_invoicing_group", "fk_progress_invoicing_group_task_line_group_id"
    ):
        op.drop_constraint(
            op.f("fk_progress_invoicing_group_task_line_group_id"),
            "progress_invoicing_group",
            type_="foreignkey",
        )
    op.create_foreign_key(
        op.f("fk_progress_invoicing_group_task_line_group_id"),
        "progress_invoicing_group",
        "task_line_group",
        ["task_line_group_id"],
        ["id"],
        ondelete="CASCADE",
    )
    # ### end Alembic commands ###


def migrate_datas():
    from alembic.context import get_bind
    from zope.sqlalchemy import mark_changed
    from caerp_base.models.base import DBSESSION

    session = DBSESSION()
    conn = get_bind()

    mark_changed(session)
    session.flush()


def upgrade():
    update_database_structure()
    migrate_datas()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # ### end Alembic commands ###
    pass
